package com.jimo.app;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.jimo.app.adp.AppListAdapter;
import com.jimo.app.databinding.ActivityAppListBinding;

import java.util.ArrayList;
import java.util.List;

public class AppListActivity extends AppCompatActivity {

    private boolean selectInjected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        @NonNull ActivityAppListBinding bind = ActivityAppListBinding.inflate(getLayoutInflater());
        setContentView(bind.getRoot());
        selectInjected=getIntent().getBooleanExtra("selectInjected",false);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        PackageManager pm = getPackageManager();
        ArrayList<PackageInfo> app = new ArrayList<>();
        AppListAdapter adp = new AppListAdapter(
                this,
                pm,
                selectInjected,
                app,
                appInfo -> {
            Intent data = new Intent();
            data.putExtra("sourceDir",appInfo.applicationInfo.sourceDir );
            data.putExtra("packageName",appInfo.applicationInfo.packageName );
            setResult(RESULT_OK, data);
            finish();
        });
        bind.list.setAdapter(adp);
        bind.list.setLayoutManager(new LinearLayoutManager(this));
        List<PackageInfo>pkginfo=new ArrayList<>();
        for (PackageInfo pkg : pm.getInstalledPackages(0)) {
            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                pkginfo.add(pkg);
            }
        }
        app.addAll(pkginfo);
    }
}